创建时间: | 2016/7/13 18:33 |
来源: | http://blog.163.com/moji_xiang/blog/static/223422103201410263520531/ |
在开发的时候碰到一个情况,数据源有100个景点,需要对给出的一个点,求距离它最近的景点,并且在前端下拉翻页的过程中,依距离顺序依次显示出来。大众点评做出了这个效果,但是以我现阶段的经验,想不出比较完美的解决方案。尤其是处理下拉翻页还能保证排序的效果,这一点是需要先对所有的点求距离,然后将所有点进行排序然后输出吗?这样效率不低吗?后来想到,mongodb有一个查询操作是geoNear,于是思考通过这种方案来解决排序效率的问题。
在网上查了一下,大概需要三步:
loc:[longitude, latitude]
属性loc
增加索引AttractionSchema.index({loc: '2d'});
使用geoNear
Model.geoNear([1,3], { maxDistance : 5, spherical : true }, function(err,results, stats) {
console.log(results);
});
或者确保有
确保有GeoJSON数据结构
{ <location field>: { type: "<GeoJSON type>" , coordinates: <coordinates> } }
AttractionSchema.index({location: '2dsphere'});
查找
// geoJson
var point = { type : "Point", coordinates : [9,9] };
Model.geoNear(point, { maxDistance : 5, spherical : true }, function(err, results, stats) {
console.log(results);
});
利用aggregate
models.Attraction.aggregate(
[{
"$geoNear": {
// "near": {
// "type": "Point",
// "coordinates": [-74.00824900000001, 40.708635]
// },
"near": [-74.00824900000001, 40.708635],
"maxDistance": 10000,
"distanceMultiplier": 6371,
"spherical": true,
"query":{cityid: '516cc44ce3c6a60f69000011'},
"distanceField": "dist.calculated",
"includelocs":"dist.location"
}
},{
"$skip": 10
},{
"$limit": 10
}],
function(err, docs) {
if (err) {
console.log(err);
} else {
docs.forEach(function(element, index){
console.log(element.cityname + ' '+element.attractions + ' '+ element.dist.calculated);
});
}
// These are not mongoose documents, but you can always cast them
}
);